package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.config.common.BaseContext;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import com.itheima.reggie.web.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @author BaiXin
 */
@Service
@Slf4j
@Transactional
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    AddressBookService addressBookService;

    @Autowired
    ShoppingCartService shoppingCartService;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderDetailService orderDetailService;

    /**
     * 用户下单
     *
     * @param order
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submit(Order order) {
        //获得当前用户id, 查询当前用户的购物车数据
        Long userId = BaseContext.getThreadLocal();

        //生成随机订单号
        String orderId = UUID.randomUUID().toString().replaceAll("-", "");
        order.setNumber(orderId);
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(LocalDateTime.now());
        order.setStatus(2);

        //根据地址id，获取收货地址信息，设置到订单
        AddressBook addressBook = addressBookService.getById(order.getAddressBookId());

        //复制数据 不复制id
        BeanUtils.copyProperties(addressBook, order, "id");

        //收货地址
        order.setAddress(new StringBuilder()
                .append(addressBook.getProvinceName())
                .append(addressBook.getCityName())
                .append(addressBook.getDetail())
                .toString());

        //购物车
        int total = 0;
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(userId);
        if (shoppingCarts.size() <= 0) {
            throw new BusinessException("购物车为空，无法下单");
        }
        //计算总额,设置到订单
        for (ShoppingCart shoppingCart : shoppingCarts) {
            total += shoppingCart.getAmount() * shoppingCart.getNumber();
        }
       order.setAmount(total);

        //订单基本信息
        int count = orderMapper.insert(order);
        if (count<=0) {
            throw new BusinessException("下单失败");
        }

        //根据购物车，生成订单详情数据
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail,"serialVersionUID");
            orderDetail.setOrderId(order.getId());
            orderDetails.add(orderDetail);
        }

        //保存订单详情数据
        boolean result = orderDetailService.saveBatch(orderDetails);
        if (!result) {
            throw new BusinessException("下单失败");
        }


        // 清空购物车
        HashMap<String, Object> condition = new HashMap<>();
        condition.put("user_id", userId);
        // 调用业务层删除本人所有购物车项
        boolean result2 = shoppingCartService.removeByMap(condition);
        if (!result2) {
            throw new BusinessException("下单失败");
        }


    }
}